package com.zhiyin.seal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhiyin.seal.dao.*;
import com.zhiyin.seal.entity.*;
import com.zhiyin.seal.entity.bo.*;
import com.zhiyin.seal.service.CompanyService;
import com.zhiyin.seal.util.BeanUtil;
import com.zhiyin.seal.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CompanyServiceImpl implements CompanyService {

    private static final String KEY = "364643c9-aa9d-42ac-bb1e-03e657939c83";

    private static final String SECRET = "e8c559fe-d035-4712-afca-5a43cc74d30c";

    private static final String API_URL = "https://api.qixin.com/APIService/enterprise/getBasicInfo?appkey=%s&secret_key=%s&keyword=%s";

    @Autowired
    CompanyDao companyDao;

    @Autowired
    CompanyUserDao companyUserDao;

    @Autowired
    CompanyDepartmentDao companyDepartmentDao;

    @Autowired
    CompanyAdminDao companyAdminDao;

    @Autowired
    AlarmRecordDao alarmRecordDao;

    @Autowired
    CompanyContractTypeDao companyContractTypeDao;

    @Autowired
    UserDao userDao;

    private String getAuthUrl(String name){
        return String.format(API_URL,KEY,SECRET,name);
    }

    @Override
    public Boolean addCompany(CompanyBo companyBo) {
        // 查询公司是否存在
        Integer count = companyDao.selectCompanyByName(companyBo.getName(),companyBo.getCreateUser());
        if(count > 0){
            return false;
        }
        CompanyEntity companyEntity = BeanUtil.copy(companyBo,CompanyEntity.class);
        return companyDao.insertCompany(companyEntity) > 0;
    }

    @Override
    public List<CompanyBo> getAllCompanyList(String keywords) {
        List<CompanyEntity> companyEntityList = companyDao.selectAllCompanyList(keywords);
        return BeanUtil.copyList(companyEntityList,CompanyBo.class);
    }

    @Override
    public List<CompanyUserBo> getMyCompanyList(Long userId) {
        List<CompanyUserEntity> companyUserEntityList = companyUserDao.getCompanyListByUserId(userId);
        return BeanUtil.copyList(companyUserEntityList,CompanyUserBo.class);
    }

    @Override
    public List<CompanyBo> getCompanyListByIds(List<Long> companyIds) {
        List<CompanyEntity> companyEntityList = companyDao.selectCompanyListByIds(companyIds);
        return BeanUtil.copyList(companyEntityList,CompanyBo.class);
    }

    @Override
    public CompanyBo getCompanyById(Long id) {
        CompanyEntity companyEntity = companyDao.selectCompanyById(id);
        return BeanUtil.copy(companyEntity,CompanyBo.class);
    }

    @Override
    public CompanyBo getCompanyByNameSingle(String companyName) {
        CompanyEntity companyEntity = companyDao.selectCompanyByNameSingle(companyName);
        if(companyEntity == null){
            return null;
        }
        return BeanUtil.copy(companyEntity,CompanyBo.class);
    }

    @Override
    public CompanyBo getLastCompanyByCreateUser(Long createUser) {
        CompanyEntity companyEntity = companyDao.getLastCompanyByCreateUser(createUser);
        return BeanUtil.copy(companyEntity,CompanyBo.class);
    }

    @Override
    public Boolean initDepartment(CompanyBo companyBo) {
        CompanyEntity companyEntity = BeanUtil.copy(companyBo,CompanyEntity.class);
        return companyUserDao.initDepartment(companyEntity) > 0;
    }

    @Override
    public Boolean addCompanyUser(Long userId, Long companyId) {
        CompanyUserEntity companyUserEntity = new CompanyUserEntity();
        companyUserEntity.setUserId(userId);
        companyUserEntity.setCompanyId(companyId);
        companyUserEntity.setCreateUser(userId);
        return companyUserDao.insertCompanyUser(companyUserEntity) > 0;
    }

    @Override
    public CompanyUserBo getLastCompanyUser(Long userId, Long companyId) {
        CompanyUserEntity companyUserEntity = companyUserDao.getLastCompanyUser(userId,companyId);
        return BeanUtil.copy(companyUserEntity,CompanyUserBo.class);
    }

    @Override
    public Boolean setDefaultCompany(CompanyUserBo companyUserBo) {
        CompanyUserEntity companyUserEntity = BeanUtil.copy(companyUserBo,CompanyUserEntity.class);
        return companyUserDao.setDefaultCompany(companyUserEntity) > 0;
    }

    @Override
    public CompanyBo getUserDefaultCompany(Long userId) {
        CompanyEntity companyEntity = companyDao.getUserDefaultCompany(userId);
        return BeanUtil.copy(companyEntity,CompanyBo.class);
    }

    @Override
    public Boolean switchCompany(Long userId, Long companyId) {
        return companyUserDao.switchCompany(userId,companyId) > 0;
    }

    @Override
    public CompanyDepartmentBo getDepartmentById(Long id) {
        return BeanUtil.copy(companyDepartmentDao.getDepartmentById(id),CompanyDepartmentBo.class);
    }

    @Override
    public List<CompanyDepartmentBo> getDepartmentListByCompanyId(Long companyId) {
        List<CompanyDepartmentEntity> companyDepartmentEntityList = companyDepartmentDao.getDepartmentListByCompanyId(companyId);
        return BeanUtil.copyList(companyDepartmentEntityList,CompanyDepartmentBo.class);
    }

    @Override
    public List<CompanyDepartmentBo> getDepartmentListByDepartmentId(Long departmentId) {
        List<CompanyDepartmentEntity> companyDepartmentEntityList = companyDepartmentDao.getDepartmentListByDepartmentId(departmentId);
        return BeanUtil.copyList(companyDepartmentEntityList,CompanyDepartmentBo.class);
    }

    @Override
    public List<CompanyUserBo> getAllUserList(Long companyId) {
        List<CompanyUserEntity> companyUserEntityList = companyUserDao.getAllUserList(companyId);
        return BeanUtil.copyList(companyUserEntityList,CompanyUserBo.class);
    }

    @Override
    public List<CompanyUserBo> getUserListByCompanyId(Long companyId) {
        List<CompanyUserEntity> companyUserEntityList = companyUserDao.getUserListByCompanyId(companyId);
        return BeanUtil.copyList(companyUserEntityList,CompanyUserBo.class);
    }

    @Override
    public List<CompanyUserBo> getUserListByDepartmentId(Long departmentId) {
        List<CompanyUserEntity> companyUserEntityList = companyUserDao.getUserListByDepartmentId(departmentId);
        return BeanUtil.copyList(companyUserEntityList,CompanyUserBo.class);
    }

    @Override
    public Long getUserDepartmentId(Long companyId, Long userId) {
        return companyUserDao.selectUserDepartmentId(companyId,userId);
    }

    @Override
    public List<Long> getSubDepartmentIds(Long departmentId) {
        return companyDepartmentDao.selectSubDepartmentIds(departmentId);
    }

    @Override
    public List<Long> getParentDepartmentIds(Long departmentId) {
        return companyDepartmentDao.selectParentDepartmentIds(departmentId);
    }

    @Override
    public Boolean addDepartment(CompanyDepartmentBo companyDepartmentBo) {
        CompanyDepartmentEntity companyDepartmentEntity = BeanUtil.copy(companyDepartmentBo,CompanyDepartmentEntity.class);
        return companyDepartmentDao.insertDepartment(companyDepartmentEntity) > 0;
    }

    @Override
    public Boolean addCompanyUser(CompanyUserBo companyUserBo) {
        CompanyUserEntity companyUserEntity = BeanUtil.copy(companyUserBo,CompanyUserEntity.class);
        return companyUserDao.insertCompanyUser(companyUserEntity) > 0;
    }

    @Override
    public Boolean moveUserUp(Long userId, Long departmentId, Long companyId) {
        return companyUserDao.updateUserDepartmentUp(userId,departmentId,companyId) > 0;
    }

    @Override
    public Boolean moveUserDown(Long userId, Long departmentId, Long companyId) {
        return companyUserDao.updateUserDepartmentDown(userId,departmentId,companyId) > 0;
    }

    @Override
    public Boolean updateDepartmentName(String name, Long id) {
        return companyDepartmentDao.updateDepartmentName(name,id) > 0;
    }

    @Override
    public Boolean removeDepartment(Long id) {
        return companyDepartmentDao.deleteDepartment(id) > 0;
    }

    @Override
    public Boolean updateUserAlias(Long userId, Long companyId, String userAlias) {
        return companyUserDao.updateUserAlias(userId,companyId,userAlias) > 0;
    }

    @Override
    public Boolean removeUser(Long userId, Long companyId) {
        return companyUserDao.removeUser(userId,companyId) > 0;
    }

    @Override
    public Boolean addCompanyAdmin(CompanyAdminBo companyAdminBo) {
        CompanyAdminEntity companyAdminEntity = BeanUtil.copy(companyAdminBo,CompanyAdminEntity.class);
        return companyAdminDao.insertCompanyAdmin(companyAdminEntity) > 0;
    }

    @Override
    public Boolean deleteCompanyAdmin(Long userId, Long companyId) {
        return companyAdminDao.deleteCompanyAdmin(userId,companyId) > 0;
    }

    @Override
    public Boolean deleteAdminFunction(Long userId, Long companyId) {
        return companyAdminDao.deleteAdminFunction(userId,companyId) > 0;
    }

    @Override
    public Boolean deleteAdminSeal(Long userId, Long companyId) {
        return companyAdminDao.deleteAdminSeal(userId,companyId) > 0;
    }

    @Override
    public Boolean joinCompany(Long companyId, Long userId) {
        return companyDao.joinCompany(companyId,userId) > 0;
    }

    @Override
    public Boolean joinCompany2(Long companyId, Long userId, String nickName) {
        return companyDao.joinCompany2(companyId,userId,nickName) > 0;
    }

    @Override
    public Boolean transferCompany(Long companyId, Long userId) {
        CompanyEntity companyEntity = companyDao.selectCompanyById(companyId);
        if(companyEntity == null){
            return false;
        } else {
            int count = companyDao.selectCompanyByName(companyEntity.getName(),userId);
            if(count > 0){
                return false;
            }
        }

        return companyDao.transferCompany(companyId,userId) > 0;
    }

    @Override
    public Boolean removeCompanyAllAdmin(Long companyId) {
        return companyAdminDao.deleteCompanyAllAdmin(companyId) > 0;
    }

    @Override
    public Boolean deleteAllAdminFunction(Long companyId) {
        return companyAdminDao.deleteAllAdminFunction(companyId) > 0;
    }

    @Override
    public Boolean deleteAllAdminSeal(Long companyId) {
        return companyAdminDao.deleteAllAdminSeal(companyId) > 0;
    }

    @Override
    public Boolean removeCompanyUser(Long companyId) {
        return companyUserDao.deleteCompanyUser(companyId) > 0;
    }

    @Override
    public List<CompanyAdminBo> getCompanyAdminList(Long companyId) {
        List<CompanyAdminEntity> companyAdminEntityList = companyAdminDao.selectCompanyAdminList(companyId);
        return BeanUtil.copyList(companyAdminEntityList,CompanyAdminBo.class);
    }

    @Override
    public List<AlarmRecordBo> getAlarmRecordList(Long companyId) {
        return BeanUtil.copyList(alarmRecordDao.selectAlarmRecordList(companyId),AlarmRecordBo.class);
    }

    @Override
    public List<CompanyContractTypeBo> getCompanyContractTypeList(Long companyId) {
        return BeanUtil.copyList(companyContractTypeDao.selectCompanyConstractTypeList(companyId),CompanyContractTypeBo.class);
    }

    @Override
    public List<CompanyContractTypeBo> getCompanyContractTypeListByParentId(Long id, Long companyId) {
        return BeanUtil.copyList(companyContractTypeDao.selectCompanyConstractTypeListByParentId(id,companyId),CompanyContractTypeBo.class);
    }

    @Override
    public Boolean addCompanyContractType(CompanyContractTypeBo companyContractTypeBo) {
        return companyContractTypeDao.insertCompanyContractType(BeanUtil.copy(companyContractTypeBo, CompanyContractTypeEntity.class)) > 0;
    }

    @Override
    public Boolean deleteCompanyContractType(Long id) {
        return companyContractTypeDao.deleteCompanyContractType(id) > 0;
    }

    @Override
    public Boolean removeCompany(Long companyId) {
        return companyDao.deleteCompany(companyId) > 0;
    }

    @Override
    public CompanyAuthBo getAuthCompany(String name) {
        CompanyAuthEntity companyAuthEntity = companyDao.selectCompanyAuth(name);
        if(companyAuthEntity != null){
            return BeanUtil.copy(companyAuthEntity,CompanyAuthBo.class);
        }

        return null;
    }

    @Override
    public CompanyAuthBo authCompany(String companyNname) {
        String url = getAuthUrl(companyNname);
        String result = HttpUtil.doGet(url);
        if(result == null)
            return null;
        try{
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer status = jsonObject.getInteger("status");
            if(status != null){
                if(status.equals(200)){
                    CompanyAuthEntity companyAuthEntity = new CompanyAuthEntity();
                    JSONObject company = jsonObject.getJSONObject("data");

                    String econKind = company.getString("econKind");
                    companyAuthEntity.setEconKind(econKind);

                    String registCapi = company.getString("registCapi");
                    companyAuthEntity.setRegistCapi(registCapi);

                    String currency_unit = company.getString("currency_unit");
                    companyAuthEntity.setCurrentUnit(currency_unit);

                    String belongOrg = company.getString("belongOrg");
                    companyAuthEntity.setBelongOrg(belongOrg);

                    String termStart = company.getString("termStart");
                    companyAuthEntity.setTermStart(termStart);

                    String historyNames = company.getString("historyNames");
                    companyAuthEntity.setHistoryNames(historyNames);

                    String revoke_date = company.getString("revoke_date");
                    companyAuthEntity.setRevokeDate(revoke_date);

                    String address = company.getString("address");
                    companyAuthEntity.setAddress(address);

                    String tags = company.getString("tags");
                    companyAuthEntity.setTags(tags);

                    String creditNo = company.getString("creditNo");
                    companyAuthEntity.setCreditNo(creditNo);

                    String domain = company.getString("domain");
                    companyAuthEntity.setDomain(domain);
                    String trade = companyDao.selectTrade(domain);
                    // 判断是否行业为空
                    if(trade == null){
                        trade = "公共管理、社会保障和社会组织";
                    }
                    companyAuthEntity.setTrade(trade);

                    String startDate = company.getString("startDate");
                    companyAuthEntity.setStartDate(startDate);

                    String scope = company.getString("scope");
                    companyAuthEntity.setScope(scope);

                    String name = company.getString("name");
                    companyAuthEntity.setName(name);

                    String operName = company.getString("operName");
                    companyAuthEntity.setOperName(operName);

                    String districtCode = company.getString("districtCode");
                    companyAuthEntity.setDistrictCode(districtCode);
                    List<String> regionList = companyDao.selectRegion(districtCode);
                    companyAuthEntity.setRegion(String.join(",",regionList));

                    String new_status = company.getString("new_status");
                    companyAuthEntity.setNewStatus(new_status);

                    String endDate = company.getString("endDate");
                    companyAuthEntity.setEndDate(endDate);

                    String checkDate = company.getString("checkDate");
                    companyAuthEntity.setCheckDate(checkDate);

                    String actualCapi = company.getString("actualCapi");
                    companyAuthEntity.setActualCapi(actualCapi);

                    String termEnd = company.getString("termEnd");
                    companyAuthEntity.setTermEnd(termEnd);

                    String revoke_reason = company.getString("revoke_reason");
                    companyAuthEntity.setRevokeReason(revoke_reason);

                    // 插入数据
                    companyDao.insertCompanyAuth(companyAuthEntity);

                    return BeanUtil.copy(companyAuthEntity,CompanyAuthBo.class);
                }
            }
        } catch (Exception ex){

        }


        return null;
    }

    @Override
    public Boolean updateCompanyAuthStatus(Long companyId) {
        return companyDao.updateCompanyAuthStatus(companyId) > 0;
    }

    @Override
    public Boolean changeCompany(Long companyId, String name) {
        return companyDao.updateChangeCompany(companyId,name) > 0;
    }

    @Override
    public UserBo getCompanyBelongUser(Long companyId) {
        CompanyEntity companyEntity = companyDao.selectCompanyById(companyId);
        if(companyEntity != null){
            CompanyUserEntity companyUserEntity = companyUserDao.selectCompanyUser(companyEntity.getBelongUser(),companyEntity.getId());
            if(companyUserEntity != null){
                UserEntity userEntity = userDao.getUserInfoById(companyUserEntity.getUserId());
                if(userEntity != null){
                    UserBo userBo = BeanUtil.copy(userEntity,UserBo.class);
                    userBo.setNickName(companyUserEntity.getUserAlias());

                    return userBo;
                }
            }
        }

        return null;
    }

    @Override
    public Integer getCompanyCount() {
        return companyDao.selectCompanyCount();
    }

    @Override
    public void buildCompanyIdListByCompanyUserList(List<CompanyUserBo> companyUserBoList, List<Long> companyIds) {
        companyIds.add(0l);
        if(companyUserBoList != null){
            for (CompanyUserBo companyUserBo : companyUserBoList){
                companyIds.add(companyUserBo.getCompanyId());
            }
        }
    }

    @Override
    public void buildUserInfoListByCompanyUserList(List<CompanyUserBo> companyUserBoList, List<UserBo> userBoList) {
        if(companyUserBoList != null){
            for (CompanyUserBo companyUserBo : companyUserBoList){
                UserEntity userEntity = userDao.getUserInfoById(companyUserBo.getUserId());
                if(userEntity != null){
                    UserBo userBo = BeanUtil.copy(userEntity,UserBo.class);
                    userBo.setNickName(companyUserBo.getUserAlias());
                    userBoList.add(userBo);
                }
            }
        }
    }

    @Override
    public void buildUserIdListByCompanyUserList(List<CompanyUserBo> companyUserBoList, List<Long> userIds) {
        userIds.add(0l);
        if(companyUserBoList != null){
            for (CompanyUserBo companyUserBo : companyUserBoList){
                userIds.add(companyUserBo.getUserId());
            }
        }
    }

    @Override
    public void buildUserIdListByCompanyList(List<CompanyBo> companyBoList, List<Long> userIds) {
        userIds.add(0l);
        if(companyBoList != null){
            for (CompanyBo companyBo : companyBoList){
                userIds.add(companyBo.getBelongUser());
            }
        }
    }

    @Override
    public void buildUserIdListByCompanyAdminList(List<CompanyAdminBo> companyAdminBoList, List<Long> userIds) {
        userIds.add(0l);
        if(companyAdminBoList != null){
            for (CompanyAdminBo companyAdminBo : companyAdminBoList){
                userIds.add(companyAdminBo.getUserId());
            }
        }
    }

    @Override
    public void buildUserInfoListByCompanyAdminList(List<CompanyAdminBo> companyAdminBoList, List<UserBo> userBoList) {
        if(companyAdminBoList != null){
            for (CompanyAdminBo companyAdminBo : companyAdminBoList){
                CompanyUserEntity companyUserEntity = companyUserDao.selectCompanyUser(companyAdminBo.getUserId(),companyAdminBo.getCompanyId());
                if(companyUserEntity !=null){
                    UserEntity userEntity = userDao.getUserInfoById(companyAdminBo.getUserId());
                    if(userEntity != null){
                        UserBo userBo = BeanUtil.copy(userEntity,UserBo.class);
                        userBo.setNickName(companyUserEntity.getUserAlias());
                        userBoList.add(userBo);
                    }
                }
            }
        }
    }

    @Override
    public void buildUserIdsByAlarmRecordList(List<AlarmRecordBo> alarmRecordBoList, List<Long> userIds) {
        userIds.add(0l);
        if(alarmRecordBoList != null){
            for (AlarmRecordBo alarmRecordBo : alarmRecordBoList) {
                if(alarmRecordBo.getCreateUser() == null){
                    continue;
                }
                userIds.add(alarmRecordBo.getCreateUser());
            }
        }
    }
}
